"""
拖拽处理组件
"""

import tkinter as tk
from tkinter import messagebox
from typing import TYPE_CHECKING

try:
    from tkinterdnd2 import DND_FILES
    DRAG_DROP_AVAILABLE = True
except ImportError:
    DRAG_DROP_AVAILABLE = False

from ...utils import FileUtils

if TYPE_CHECKING:
    from ..main_window import MainWindow


class DragDropHandlerMixin:
    """拖拽处理 Mixin 类"""
    
    def _setup_drag_drop(self: 'MainWindow'):
        """设置拖拽支持"""
        if not DRAG_DROP_AVAILABLE:
            self.logger.info("拖拽功能不可用（tkinterdnd2未安装）")
            return
        
        try:
            # 注册拖拽目标
            self.original_canvas.drop_target_register(DND_FILES)
            self.original_canvas.dnd_bind('<<Drop>>', self._on_drop)
            self.original_canvas.dnd_bind('<<DragEnter>>', self._on_drag_enter)
            self.original_canvas.dnd_bind('<<DragLeave>>', self._on_drag_leave)
            
            # 更新左侧框架标题提示
            self.left_frame.config(text="原始图片（点击选择对象 / 拖拽图片到此处）")
            
            self.logger.info("拖拽功能已启用")
        except Exception as e:
            self.logger.warning(f"设置拖拽功能失败: {e}")
    
    def _on_drag_enter(self: 'MainWindow', event):
        """拖拽进入事件"""
        # 添加视觉反馈
        self.original_canvas.config(cursor="hand2")
        self.update_status("松开鼠标即可加载图片")
        return event.action
    
    def _on_drag_leave(self: 'MainWindow', event):
        """拖拽离开事件"""
        # 恢复默认
        self.original_canvas.config(cursor="crosshair")
        if self.image is None:
            self.update_status("就绪")
        return event.action
    
    def _on_drop(self: 'MainWindow', event):
        """拖拽放下事件"""
        # 恢复光标
        self.original_canvas.config(cursor="crosshair")
        
        # 获取文件路径
        files = event.data
        
        # 处理路径（tkinterdnd2返回的路径可能带有大括号）
        if files.startswith('{') and files.endswith('}'):
            files = files[1:-1]
        
        # 分割多个文件（只取第一个）
        file_list = files.split('} {') if '} {' in files else [files]
        file_path = file_list[0].strip()
        
        self.logger.info(f"拖拽文件: {file_path}")
        
        # 验证文件是否是图片
        if not FileUtils.is_image_file(file_path):
            messagebox.showwarning(
                "警告",
                f"不支持的文件格式！\n\n仅支持图片文件：\n.png, .jpg, .jpeg, .bmp, .tiff",
                parent=self.root
            )
            self.update_status("就绪")
            return event.action
        
        # 加载图片
        self._load_image_from_path(file_path)
        
        return event.action

